package com.example.hello.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.hello.dto.LoginDTO;
import com.example.hello.entity.Employee;
import com.example.hello.exception.BusinessException;
import com.example.hello.mapper.EmployeeMapper;
import com.example.hello.service.AuthService;
import com.example.hello.config.JwtConfig;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.BCrypt;

import javax.crypto.SecretKey;
import java.util.Date;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    
    private final EmployeeMapper employeeMapper;
    private final SecretKey jwtSecretKey;
    private final JwtConfig jwtConfig;
    
    @Override
    public String login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        log.info("用户尝试登录: {}", username);
        
        // 查询用户
        Employee employee = employeeMapper.selectByUsername(username);
        if (employee == null) {
            log.warn("用户名不存在: {}", username);
            throw new BusinessException("用户名或密码错误");
        }
        
        // 验证密码
        try {
            if (!verifyPassword(loginDTO.getPassword(), employee.getPassword())) {
                log.warn("密码错误: {}", username);
                throw new BusinessException("用户名或密码错误");
            }
            
            // 生成token
            String token = generateToken(employee);
            log.info("用户 {} 登录成功", username);
            return token;
            
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("登录过程出错: ", e);
            throw new BusinessException("系统错误，请稍后重试");
        }
    }
    
    private boolean verifyPassword(String rawPassword, String hashedPassword) {
        return BCrypt.checkpw(rawPassword, hashedPassword);
    }
    
    private String generateToken(Employee employee) {
        return Jwts.builder()
            .setSubject(employee.getUsername())
            .claim("employeeId", employee.getId())
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + jwtConfig.getExpiration()))
            .signWith(jwtSecretKey)
            .compact();
    }
    
    public static String encryptPassword(String rawPassword) {
        return BCrypt.hashpw(rawPassword);
    }
} 